# -*- coding: utf-8 -*-
import time
import logging
import os
from logging.handlers import RotatingFileHandler

project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(project_dir)
log_path = project_dir + "\log"
print(log_path)      # log文件的路径


"""
log类
"""


class Log(logging.Logger):
    def __init__(self, logname):
        # super(MyLogger, self).__init__(filename)
        # 当前时间
        nowtime = time.strftime("-%Y%m%d-%H%M%S", time.localtime())
        filename = log_path + logname + nowtime + '.log'
        logging.Logger.__init__(self, filename)

        # 设置日志格式
        fmtHandler = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)s][%(levelname)s] %(message)s')

        # 终端log输出流设置
        try:
            consoleHd = logging.StreamHandler()
            consoleHd.setLevel(logging.INFO)   # 日志输出等级
            consoleHd.setFormatter(fmtHandler)
            self.addHandler(consoleHd)
        except Exception as reason:
            self.error("%s" % reason)

            # 设置log文件
        try:
            os.makedirs(os.path.dirname(log_path))
        except Exception as reason:
            print(reason)
            pass
        try:
            # 设置回滚日志,每个日志最大10M,最多备份5个日志
            fileHd = logging.handlers.RotatingFileHandler(
                filename, maxBytes=10 * 1024 * 1024, backupCount=5)
            # fileHd = logging.FileHandler(filename)
            fileHd.setLevel(logging.INFO)
            fileHd.setFormatter(fmtHandler)
            self.addHandler(fileHd)
        except Exception as reason:
            self.error("%s" % reason)

        return


logger = Log('test01') 

# if __name__ == '__main__':
#     # 使用Log类:
#     # 1.创建一个Log对象，括号里面是log文件的名称
#     logger = Log('test01') 
#     # 2.输出info级别的log
#     logger.info("---this is info")

#     # # 也可以再创建一个对象来输出error级别的log
#     test2 = Log('test02')
#     test2.error("---this is error")
